package top.krwlc.server.controller;

import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.krwlc.server.message.UserMessage;
import top.krwlc.server.pojo.User;
import top.krwlc.server.service.ServiceResult;
import top.krwlc.server.service.UserService;
import top.krwlc.server.util.DigestUtil;

import javax.servlet.http.HttpSession;

/**
 * krwlc
 * top.krwlc.server.controller
 *
 * @author Lanscarlos
 * @since 2022-04-05 10:47
 */
@RestController
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
@RequestMapping("/user")
public class UserController extends Controller {

    @Autowired
    public UserService service;

    /**
     * 登入用户
     *
     * @param username 用户名
     * @param password 密码
     * */
    @RequestMapping(value = "/login")
    public Object login(HttpSession session, JsonObject json, String username, String password) {

        // 判断用户是否已登录
        if (session.getAttribute("log") != null) {
            json.addProperty("status", false);
            json.addProperty("message", service.message.LOGIN_DUPLICATE);
            return json;
        }

        ServiceResult result = service.login(username, DigestUtil.digest(password));
        if (result.getStatus() == 0x200) {
            json.addProperty("status", true);
            json.add("user", toJson(result.getObject()));
            session.setAttribute("log", result.getObject());
        } else {
            json.addProperty("status", false);
        }
        json.addProperty("message", result.getMessage());
        return json;
    }

    /**
     * 登出用户
     * */
    @RequestMapping(value = "/logout")
    public Object logout(HttpSession session, JsonObject json) {
        if (session.getAttribute("log") != null) {
            json.addProperty("status", true);
            json.addProperty("message", service.message.LOGOUT_SUCCEEDED);
            session.removeAttribute("log");
        } else {
            json.addProperty("status", false);
            json.addProperty("message", service.message.LOGOUT_UNLISTED);
        }
        return json;
    }

    /**
     * 注册用户
     *
     * @param username 用户名
     * @param password 密码
     * */
    @RequestMapping(value = "/register")
    public Object register(
            JsonObject json,
            String display,
            String password,
            String username,
            String identityCode,
            String phone
    ) {

        ServiceResult result = service.register(display, DigestUtil.digest(password), username, identityCode, phone);
        if (result.getStatus() == 0x200) {
            json.addProperty("status", true);
            json.add("user", toJson(result.getObject()));
        } else {
            json.addProperty("status", false);
        }
        json.addProperty("message", result.getMessage());
        return json;
    }

}
